<template>
<div>
  <a-modal title="离职申请" :width="width" :visible="visible" @ok="ok" @cancel="cancel">
    <template #footer>
      <a-button key="back" @click="cancel">关闭</a-button>
      <a-button  type="primary" @click="ok">保存</a-button>
      <a-button type="primary" @click="fnSubmitApply">提交申请</a-button>
    </template>
    <a-table :dataSource="rows"
          :columns="columns" :pagination="false" bordered
          :expandedRowKeys="expandedRowKeys"
          @expandedRowsChange="expandedRowsChange">
      <template #expandedRowRender>
        <a-form-model ref="form" :form="rows[num].form" style="margin-top: 16px">
          <a-row>
            <a-col :span="6">
              <a-form-item label="减员原因" name="jyreason">
                <a-input placeholder="请输入减员原因" v-model="rows[num].jyreason" style="width:60%"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="减员时间" name="jydate">
                <a-date-picker v-model="rows[num].jydate"></a-date-picker>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="停薪时间" name="txdate">
                <a-date-picker v-model="rows[num].txdate"></a-date-picker>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="申请人希望最后工作日" name="xwdate">
                <a-date-picker v-model="rows[num].xwdate"></a-date-picker>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="6">
              <a-form-item label="最后工作日" name="lastworkdate">
                <a-date-picker v-model="rows[num].lastworkdate"></a-date-picker>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="工资发放截止时间" name="jzdate">
                <a-date-picker v-model="rows[num].jzdate"></a-date-picker>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="6">
              <a-form-item label="员工离职交接表" name="image1">
                <a-upload
                  v-model="rows[num].image1"
                  list-type="picture-card"
                  :multiple="false"
                  :before-upload="beforeUpload1"
                  @preview="handlePreview"
                  :remove="remove1"
                  accept=".doc,.docx,.xls,.xlsx.pdf,image/*">
                  <div v-if="thisShow1">
                    <plus-outlined />
                    <div class="ant-upload-text">上传</div>
                  </div>
                </a-upload>
                <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                  <img alt="example" style="width: 100%" :src="previewImage" />
                </a-modal>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="离职人员个人劳保服装发放情况确认单" name="image2">
                <a-upload
                  v-model="rows[num].image2"
                  list-type="picture-card"
                  :multiple="false"
                  :before-upload="beforeUpload2"
                  @preview="handlePreview"
                  :remove="remove2"
                  accept=".doc,.docx,.xls,.xlsx.pdf,image/*">
                  <div v-if="thisShow2">
                    <plus-outlined />
                    <div class="ant-upload-text">上传</div>
                  </div>
                </a-upload>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="个人劳动保护用品登记卡" name="image3">
                <a-upload
                  v-model="rows[num].image3"
                  list-type="picture-card"
                  :multiple="false"
                  :before-upload="beforeUpload3"
                  @preview="handlePreview"
                  :remove="remove3"
                  accept=".doc,.docx,.xls,.xlsx.pdf,image/*">
                  <div v-if="thisShow3">
                    <plus-outlined />
                    <div class="ant-upload-text">上传</div>
                  </div>
                </a-upload>
              </a-form-item>
            </a-col>
            <a-col :span='6'>
                <a-button  type="primary" @click="onDownFile(rows[num].id)">导出附件</a-button>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24">
              <a-form-item label="离职原因" name="lizhireason">
                <a-textarea placeholder="请输入离职原因" v-model="rows[num].lizhireason"></a-textarea>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24">
              <a-form-item label="离职面谈记录" name="mtjilu">
                <a-textarea placeholder="请输入离职面谈记录" v-model="rows[num].mtjilu"></a-textarea>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24">
              <a-form-item label="备注" name="remark">
                <a-textarea placeholder="请输入备注" v-model="rows[num].remark"></a-textarea>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form-model>
      </template>
    </a-table>
  </a-modal>
  <!--提交申请表单-->
        <a-modal title="提交审批" v-model="modalVisible" :mask-closable="false" :width="500" :footer="null">
          <div v-if="modalVisible">
            <a-form-item label="选择审批人" v-show="showAssign">
              <a-select style="width: 100%"
                v-model="form.assignees"
                placeholder="请选择"
                :allowClear="true"
              >
              <a-select-option v-for="(item, i) in assigneeList" :key="i" :value="item.username">{{item.realname}}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="下一审批人" v-show="isGateway">
              <a-alert  type="info" showIcon message="分支网关处不支持自定义选择下一审批人，将自动下发给所有可审批人。">，将发送给下一节点所有人</a-alert>
            </a-form-item>
            <a-form-item label="优先级" prop="priority">
              <a-select v-model="form.priority" placeholder="请选择" :allowClear="true" style="width: 100%">
                <a-select-option :value="0">普通</a-select-option>
                <a-select-option :value="1">重要</a-select-option>
                <a-select-option :value="2">紧急</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="消息通知">
              <a-checkbox v-model="form.sendMessage">站内消息通知</a-checkbox>
              <a-checkbox v-model="form.sendSms" disabled>短信通知</a-checkbox>
              <a-checkbox v-model="form.sendEmail" disabled>邮件通知</a-checkbox>
            </a-form-item>
            <div slot="footer">
              <a-button type="text" @click="cancelTijiao">取消</a-button>
              <div style="display:inline-block;width: 20px;"></div>
              <a-button type="primary" :disabled="submitLoading" @click="applySubmit">提交</a-button>
            </div>
          </div>
      </a-modal>
      </div>
</template>

<script>
const columns = [
  { dataIndex: 'id', key: 'id', title: 'ID' },
  { dataIndex: 'name', key: 'name', title: '姓名' },
  { dataIndex: 'borth', key: 'borth', title: '生日' },
  { dataIndex: 'sfzh', key: 'sfzh', title: '身份证' },
]
import { downFile,addLizhi,postAction } from '@/api/manage'
export default {
  props: {
    visible: false,
    rows: [],
  },
  created() {
    this.rows = this.rows.map(item=>{
      item.image1 = ''
      item.image2 = ''
      item.image3 = ''
      return item
    })
  },
  data() {
    return {
      thisShow1: false,
      thisShow2: false,
      thisShow3: false,
      previewVisible: false,
      previewImage: '',
      columns,
      form:{
          priority:0,
          assignees:[],
          sendMessage:true
        },
      width: 1400,
      visible: false,
      expandedRowKeys:[],
      num: 0,
      modalVisible:false,
      assigneeList:[],
      submitLoading: false,
      url:{
        getFirstNode:'/actProcessIns/getFirstNode',
          applyBusiness:'/actBusiness/apply'
      }
    }
  },
  methods: {
    applySubmit() {
                if (this.showAssign && this.form.assignees.length < 1) {
                  this.error = "请至少选择一个审批人";
                  this.$message.error(this.error)
                  return;
                } else {
                  this.error = "";
                }
                this.submitLoading = true;
                var params = Object.assign({},this.form);
               // params.assignees = params.assignees.join(",")
                let that = this;
                this.postFormAction(this.url.applyBusiness,params).then(res => {
                  if (res.success) {
                    this.$message.success("操作成功");
                   // that.loadData();
                    that.modalVisible = false;
                    that.cancel()
                  }else {
                    this.$message.error(res.message)
                  }
                }).finally(()=>this.submitLoading = false);
             },
    //提交申请
    fnSubmitApply(){
      const ids=this.rows.map(item=>{
        return item.lizhiid
      })
       
        var params={
          type:2,
          ids:ids.toString()
        }
      postAction('/bj/bjIdcardfk/saveActBussinessDataBeforApprove', params).then((res) => {
            console.log("提审:"+JSON.stringify(res))
             if (res.success) {
                this.apply(res.result);
             } else {
               this.$message.error('失败')
             }
        })
    },
    apply(v) {
              if (!v.procDefId || v.procDefId == "null") {
                this.$message.error("流程定义为空");
                return;
              }
              this.form.id = v.id;
              this.form.procDefId = v.procDefId;
              this.form.title = v.title;
              // 加载审批人
              this.getAction(this.url.getFirstNode,{procDefId:v.procDefId}).then(res => {
                if (res.success) {
                  if (res.result.type == 3 || res.result.type == 4) {
                    this.isGateway = true;
                    this.modalVisible = true;
                    this.form.firstGateway = true;
                    this.showAssign = false;
                    this.error = "";
                    return;
                  }
                  this.form.firstGateway = false;
                  this.isGateway = false;
                  if (res.result.users && res.result.users.length > 0) {
                    this.error = "";
                    this.assigneeList = res.result.users;
                    // 默认勾选
                   // let ids = [];
                   // res.result.users.forEach(e => {
                   //   ids.push(e.username);
                   // });
                    //this.form.assignees = ids;
                    this.form.assignees = [];
                    this.showAssign = true;
                  } else {
                    this.form.assignees = [];
                    this.showAssign = true;
                    this.error = '审批节点未分配候选审批人员，请联系管理员！';
                  }
                  if (this.error){
                    this.$message.error(this.error)
                    return;
                  }
                  this.modalVisible = true;
                }else {
                  this.$message.error(res.message)
                }
              });

            },
            cancelTijiao(){
               var id=this.form.id;
                postAction('/bj/bjIdcardfk/deleteActBussinessById', { actBussinessid: id }).then((res) => {
                    if (res.success) {
                       this.modalVisible = false;
                    } else {
                      this.$message.error('失败')
                    }
                 })
             },
    ok() {
      var count = 0
      this.rows.forEach((item,index,array)=>{
          if(item.jyreason == '' || item.jydate == null
           || item.txdate == '' || item.xwdate == null
            || item.lizhireason == '' || item.lastworkdate == null
             || item.mtjilu == '' || item.jzdate == null
              
              || item.jyreason == null || item.jydate == ''
           || item.txdate == null || item.xwdate == ''
            || item.lizhireason == null || item.lastworkdate == ''
             || item.mtjilu == null || item.jzdate == ''
               ){
            this.$message.error('请补全' + item.name + '信息')
            count++
          }
      })
      // || item.image1 == '' || item.image2 == null || item.image3 == '' || item.image1 == null || item.image2 == '' || item.image3 == null
      if(count == 0){
        //console.log(this.rows)
        const names=[]
         this.rows.forEach((item)=>{
         
            if(item.image1 == '' || item.image2 == null || item.image3 == '' || item.image1 == null || item.image2 == '' || item.image3 == null){
               names.push(item.name)
            }
        })
        if(names.length>0){
          const that=this;
            this.$confirm({
                  title: '提示',
                  content: names.toString()+'有文件未上传，是否要继续保存?',
                  onOk() {
                    that.putaddLizhi(that.rows)
                  },
                  onCancel() {},
                });
        }else{
          this.putaddLizhi(this.rows)
        }
        console.log("names:"+JSON.stringify(names))
        
       // this.$emit('ok',this.rows)
      }
    },
    putaddLizhi(row){
      addLizhi(row).then(res=>{
         // console.log("离职保存:"+JSON.stringify(res))
         if(res.success){
            const result=res.result
            this.rows.forEach((item)=>{
                result.forEach((it)=>{
                  
                  if(it.sfzh==item.sfzh){
                      item.lizhiid=it.lizhiid
                  }
                })
            })
            this.$message.success("保存成功");
         }else{
           this.$message.error('失败')
         }
           
      })
    },
    //导出附件
    onDownFile(id){

        downFile('/bj/bjQuit/exportFujian',{ygid:id}).then(res=>{
            if (!res) {
                this.$message.warning("文件下载失败")
                return
              }
              if (typeof window.navigator.msSaveBlob !== 'undefined') {
                window.navigator.msSaveBlob(new Blob([res],{type: 'application/vnd.ms-excel'}), '附件.xlsx')
              }else{
                let url = window.URL.createObjectURL(new Blob([res],{type: 'application/vnd.ms-excel'}))
                let link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute('download', '附件.xlsx')
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link); //下载完成移除元素
                window.URL.revokeObjectURL(url); //释放掉blob对象
              }
        })
    },
    cancel() {
      this.$emit('RZC','')
      this.$emit('close')
    },
    expandedRowsChange(expandedRows){
      var index=expandedRows[expandedRows.length-1]
      this.expandedRowKeys=[index];
      this.num=index;
      if(this.num != undefined){
        if(this.rows[this.num].image1 == ''){
          this.thisShow1 = true
        }else{
          this.thisShow1 = false
        }
        if(this.rows[this.num].image2 == ''){
          this.thisShow2 = true
        }else{
          this.thisShow2 = false
        }
        if(this.rows[this.num].image3 == ''){
          this.thisShow3 = true
        }else{
          this.thisShow3 = false
        }
      }
    },
    remove1(){
      this.thisShow1 = true
    },
    remove2(){
       this.thisShow2 = true
    },
    remove3(){
      this.thisShow3 = true
    },
    handleCancel() {
      this.previewVisible = false;
    },
    beforeUpload1(file){
      this.getBase64(file).then(res => {
        this.rows[this.num].image1 = res
      })
      this.thisShow1 = false
      return false
    },
    beforeUpload2(file){
      this.getBase64(file).then(res => {
        this.rows[this.num].image2 = res
      })
      this.thisShow2 = false
      return false
    },
    beforeUpload3(file){
      this.getBase64(file).then(res => {
        this.rows[this.num].image3 = res
      })
      this.thisShow3 = false
      return false
    },
    handlePreview(file) {
      this.previewImage = file.thumbUrl
      this.previewVisible = true;
    },
    getBase64(file) {
      return new Promise((resolve, reject) => {
        let reader = new FileReader();
        let fileResult = "";
        reader.readAsDataURL(file);
　　　　　//开始转
        reader.onload = function() {
          fileResult = reader.result;
        };
　　　　　//转 失败
        reader.onerror = function(error) {
          reject(error);
        };
　　　　　//转 结束  咱就 resolve 出去
        reader.onloadend = function() {
          resolve(fileResult);
        };
      });
    }
  }
}
</script>

<style>
</style>